package com.magima.core.repository;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

public class SingleFileRepository extends Repository{
	protected String mFilepath;
	protected Properties mProperties;
	public SingleFileRepository(StringProcessor processor, String filepath) {
		super(processor);
		mFilepath = filepath;
		mName = filepath;
	}
	public SingleFileRepository(String filepath) {
		this(null, filepath);
	}
	
	@Override
	public void saveString(String data) {
		File file = new File(mFilepath);
		if ( !file.exists() ) {
			File dir = new File(file.getParent());
			if (!dir.exists() && !dir.mkdirs()) {
		        
		    }
		}
		
		BufferedWriter out;
		try {
			out = new BufferedWriter(new FileWriter(mFilepath));
			out.write( mProcessor.encodeString(data));
	        out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public String loadString() {
		BufferedReader in;
		String str = "";
		try {
			in = new BufferedReader(new FileReader(mFilepath));
			String line;
			while ( (line = in.readLine()) != null )
				str += line;
	        in.close();
	        return mProcessor.decodeString(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public void remove(){
		File f = new File(mFilepath);
		if ( f.exists() )
			f.delete();
	}
}
